<template>
  <div v-if="!signUpView" class="login-form-wrapper">
    <div class="login-form-title">{{ signUpTitle }}</div>
    <div class="login-form-sub-title">{{ signUpSubTitle }}</div>
    <div class="login-form-error-msg">{{ errorMessage }}</div>
    <a-form
      ref="signUpForm"
      :model="signUpForm"
      class="login-form"
      layout="inline"
      @submit="handleSubmit"
    >
      <a-form-item field="name" label="姓名">
        <a-input v-model="signUpForm.name" placeholder="请输入姓名" />
      </a-form-item>
      <a-form-item field="phone" label="手机号">
        <a-input v-model="signUpForm.phone" placeholder="请输入手机号码" />
      </a-form-item>
      <a-form-item field="code" label="验证码">
        <a-input v-model="signUpForm.code" placeholder="请输入短信验证码" />
      </a-form-item>
      <a-form-item field="gender" label="性别">
        <a-radio-group
          v-model="signUpForm.gender"
          :options="genderOptions"
          :default-value="'MALE'"
        >
          <template #label="{ data }">
            <a-tag>{{ data.label }}</a-tag>
          </template>
        </a-radio-group>
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit" long :loading="loading"
            >提交</a-button
          >
        </a-space>
      </a-form-item>
    </a-form>
  </div>
  <div v-else class="login-form-wrapper">
    <div class="login-form-title">{{ '入职通知' }}</div>
    <div class="login-form-sub-title">
      {{ signUpView.status?.desc }}
    </div>
    <a-space :size="16" direction="vertical">
      <a-button type="text" long class="login-form-register-btn">
        去登录
      </a-button>
    </a-space>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import useLoading from '@/hooks/loading';
  import { Gender } from '@/api/enumObj';
  import { doUserSignUp } from '@/api/idm/user';
  import { useRoute, useRouter } from 'vue-router';
  import {
    ShortLinkInstanceView,
    ShortLinkInstanceQry,
    ShortLinkInstanceExpand,
  } from '@/types/comp/router/short-link';
  import { fetchShortLinkInstance } from '@/api/comp/router/short-link';
  import { useUserStore } from '@/store';
  import { isLogin } from '@/utils/auth';
  import { SignUpCmd, SignUpView } from '@/types/idm/user';
  import useRequest from '@/hooks/request';
  import { RadioOption } from '@arco-design/web-vue/es/radio/interface';

  const router = useRouter();
  const { loading, setLoading } = useLoading();
  // 性别数据
  const genderOptions = Gender.map((e) => {
    return {
      value: e.name,
      label: e.desc,
    };
  }) as RadioOption[];
  const signUpTitle = ref('Offer 来啦！');
  const signUpSubTitle = ref('');
  const errorMessage = ref('');
  const shortLinkInstanceExpand = ref({} as ShortLinkInstanceExpand);

  // 进入页面之后执行的第一个函数
  const onPageLoad = async () => {
    const { user } = useUserStore();
    if (isLogin() && user.id) {
      const { redirect } = router.currentRoute.value.query;
      await router.push({
        name: (redirect as string) || 'PlatIdmOrgEmp',
        query: {},
      });
      return;
    }
    const route = useRoute();
    const shortInstanceQry = { router: route.query.r } as ShortLinkInstanceQry;
    const { response: shortLinkInstance } = useRequest<ShortLinkInstanceView>(
      fetchShortLinkInstance.bind(null, shortInstanceQry),
      {} as ShortLinkInstanceView
    );
    shortLinkInstanceExpand.value = shortLinkInstance.value
      .expand as ShortLinkInstanceExpand;
    const { inviterName, companyName, departmentName } =
      shortLinkInstanceExpand.value.params;
    signUpSubTitle.value = `${inviterName}邀请您加入${companyName}-${departmentName}团队`;
  };
  onPageLoad();

  const signUpView = ref({} as SignUpView);
  const register = async (cmd: SignUpCmd) => {
    if (loading.value) return;
    setLoading(true);
    try {
      const signUpViewRes = await doUserSignUp(cmd);
      signUpView.value = signUpViewRes.data;
    } catch (err) {
      errorMessage.value = (err as Error).message;
    } finally {
      setLoading(false);
    }
  };

  // 员工注册表单
  const signUpForm = ref({
    scene: '',
    name: '',
    phone: '',
    code: '',
    gender: 'MALE',
  });

  const handleSubmit = ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (errors) {
      console.error('sign-up err: ', errors);
      return;
    }
    const { companyId, departmentId, inviterId } =
      shortLinkInstanceExpand.value.params;
    register({
      scene: 'EMPLOYEE_PC',
      phone: values.phone,
      code: values.code,
      employee: {
        companyId: companyId as number,
        departmentId: departmentId as number,
        name: values.name,
        gender: values.gender,
        inviterId: inviterId as number,
      },
    } as SignUpCmd);
  };
</script>

<style lang="less" scoped>
  .login-form {
    &-wrapper {
      width: 420px;
    }

    &-title {
      color: var(--color-text-1);
      font-weight: 500;
      font-size: 24px;
      line-height: 32px;
    }

    &-sub-title {
      color: var(--color-text-3);
      font-size: 16px;
      line-height: 24px;
    }

    &-error-msg {
      height: 32px;
      color: rgb(var(--red-6));
      line-height: 32px;
    }

    &-password-actions {
      display: flex;
      justify-content: space-between;
    }

    &-register-btn {
      color: var(--color-text-3) !important;
    }
  }
</style>
